package com.kgcx.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.controller.BaseController;
import com.kgcx.common.utils.HttpRequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 吴刚林
 * @date 2017/11/30
 */
@Api(description = "微信接口", tags = "微信接口")
@RestController
@RequestMapping("wx")
public class WxControler extends BaseController {
    private String appId = "wxd24dd16522019ae6";
    private String appSecret = "81cf77a402fe847ba93324cde521ae58";

    @ApiOperation(value = "获取微信openid", httpMethod = "GET", notes = "这是查询微信openid的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "code", required = true, paramType = "query", dataType = "String", dataTypeClass = String.class),
    })
    @GetMapping("getLiteAppOpenid")
    public ReturnData<String> getLiteAppOpenid(@RequestParam String code) throws IOException {
        // 获取access_token
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", appSecret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        String xml = HttpRequestUtil.sendRequestByGet("https://api.weixin.qq.com/sns/oauth2/access_token", params);
        logger.info(xml);
        // 返回的result成功结果取出access_token：
        Map<String, String> map = JSONObject.parseObject(xml, Map.class);
        String openid = map.get("openid");
        logger.info("openid=" + openid);
        return new ReturnData<>(openid);
    }
}
